import {
  getBaseUrl,
  requestUtil,
  getWxLogin,
  getUserProfile
} from '../../utils/requestUtil.js';
import regeneratorRuntime from '../../lib/runtime/runtime';
// pages/cart/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    baseUrl: '',
    cart:[],
    totalPrice:0,
    totalNum:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const baseUrl = getBaseUrl();
    this.setData({
      baseUrl
    })
  },



  //重新计算底部工具栏：全选、总价、总数量、重新设置缓存
  setCart(cart){
    //获取产品的总价格,获取产品的总数量
    cart = cart.filter(v=>v.checked)
    let totalPrice = 0
    let totalNum = 0 
    cart.forEach(v=>{
      totalPrice += v.price*v.num
      totalNum += v.num
    });
    this.setData({
      cart,
      totalPrice,
      totalNum
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  //处理订单支付
  async handleOrderPay(){
    // wx.login({
    //   success: (res) => {
    //     console.log(res)
    //   },
    // })

    // wx.getUserProfile({
    //   desc: '获取用户信息',
    //   success:(res)=>{
    //     console.log(res.userInfo.avatarUrl,res.userInfo.nickName)
    //   }
    // })

    // let res = await getWxLogin();
    // console.log(res.code)
    // let res2 = await getUserProfile();
    // console.log(res2.userInfo.avatarUrl,res2.userInfo.nickName)
    const token = wx.getStorageSync('token')
    if(!token){
      Promise.all([getWxLogin(),getUserProfile()]).then((res)=>{
        console.log(res[0].code)
        console.log(res[1].userInfo.avatarUrl,res[1].userInfo.nickName)
        let loginParam={
          code:res[0].code,
          nickName:res[1].userInfo.nickName,
          avatarUrl:res[1].userInfo.avatarUrl
        }
        //个人中心页面调用
        wx.setStorageSync('userInfo', res[1].userInfo)
        this.wxlogin(loginParam)
      })
    }else{
      console.log("token存在")
      //走支付
      //创建订单
      this.createOrder();

    }

  },

  /**
   * 请求后端获取用户token
   * @param {*} loginParam 
   */
  async wxlogin(loginParam){
    const result=await requestUtil({url:"/user/wxlogin",data:loginParam,method:"post"});
    const token = result.data.token
    console.log(token)
    if(result.code === 200){
      //把token存储到缓存
      wx.setStorageSync('token', token)
      //创建订单
      this.createOrder();
    }
  },

  /**
   * 创建订单
   */
  async createOrder(){
    const totalPrice = this.data.totalPrice
    const address = this.data.address.provinceName+ this.data.address.cityName+ this.data.address.countyName
    const consignee = this.data.address.userName
    const telNumber = this.data.address.telNumber
    //携带商品详情
    let goods = [];
    this.data.cart.forEach(v=>goods.push({
        goodsId:v.id,
        goodsNumber:v.num,
        goodsPrice:v.price,
        goodsName:v.name,
        goodsPic:v.proPic
    }))
    const orderParam = {
      totalPrice,
      address,
      consignee,
      telNumber,
      goods
    }
    const res = await requestUtil({url:"/my/order/create",method:"POST",data:orderParam})
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const address = wx.getStorageSync('address')
    const cart = wx.getStorageSync('cart') || []
    this.setData({
      address
    })
    this.setCart(cart)
  }
})